<template>
  <div class="page-cinemas-search">
    <VanSearch v-model="keyword" placeholder="请输入搜索关键词" show-action @cancel="onCancel" />

    <div class="container">
      <!-- 影院列表 -->
      <CinemaList v-show="displayCinemas.length > 0" :list="displayCinemas" @click="onJump" />

      <!-- 历史搜索记录 -->
      <History v-show="displayCinemas.length === 0" ref="historyRef" />
    </div>
  </div>
</template>

<script lang="ts" setup name="cinemas-search">
import { getCinemaList } from '@/api'
import History from './components/history.vue'
import { useCityStore } from '@/stores/city'
import { calcDistance } from '@/utils'

const router = useRouter()
const { curCityId } = storeToRefs(useCityStore())

const historyRef = ref<InstanceType<typeof History> | null>(null)
const cinemas = ref<ICinema[]>([])
const keyword = ref<string>('')

// 搜索结果
const displayCinemas = computed(() => {
  if (!keyword.value) return []
  return cinemas.value.filter((item) => item.name.includes(keyword.value))
})

// 取消
function onCancel() {
  router.back()
}

// 搜索到的影院跳转
function onJump(cinema: ICinema) {
  // 1. 将当前影院添加到历史记录中
  historyRef.value?.add(cinema)

  // 2. 页面跳转
  router.push({ name: 'city' })
}

watchEffect(async () => {
  const { cinemas: list } = await getCinemaList({
    cityId: curCityId.value,
    ticketFlag: 0
  })
  cinemas.value = list
    .map((item) => ({
      ...item,
      distance: calcDistance(item.gpsAddress, '113.8394:22.6299')
    }))
    .sort((a, b) => a.distance - b.distance)
})

onUnmounted(() => {
  console.log('搜索页面卸载')
})
</script>

<style scoped>
.page-cinemas-search {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.container {
  flex: 1;
  overflow-y: auto;
}
</style>
